package cn.gx.kevin.config;

import cn.gx.kevin.Utils.LogParams;
import cn.gx.kevin.Utils.LogTasks;
import cn.gx.kevin.Utils.WebConstants;
import cn.gx.kevin.common.bootenv.SpringContextUtil;
import cn.gx.kevin.common.thread.ExecuteThreadTask;
import cn.gx.kevin.common.thread.OperatorDataHolder;
import cn.gx.kevin.common.thread.UrlInfoThreadHodler;
import cn.gx.kevin.common.ui.AdminControllerHelper;
import cn.gx.kevin.common.user.ILoginUserContext;
import cn.gx.kevin.common.user.LoginUser;
import cn.gx.kevin.common.utils.IRequestInterceptor;
import cn.gx.kevin.common.utils.SysConfigParams;
import cn.gx.kevin.common.utils.UrlInfo;
import cn.gx.kevin.service.IFuncService;
import org.apache.commons.lang3.StringUtils;
import org.redisson.misc.Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 日志拦截器
 */
public class LogInterceptor  implements IRequestInterceptor {



    private static final Logger logger = LoggerFactory.getLogger(LogInterceptor.class);
    static ILoginUserContext userContext = null;

    static IFuncService funcService = null;

    static Set<String> logSkipCmdSet = new HashSet<>();

    public static boolean currentRequestNeed2Log(){
        boolean need2log = need2log(UrlInfoThreadHodler.get());
        return need2log;
    }

    public static boolean need2log(UrlInfo urlInfo){
        String url = urlInfo.getUrl();
        if(url.contains("/page/") && "GET".equals(urlInfo.getMethod())){
            return false;
        }
        if(logSkipCmdSet.size() == 0){
           String strSkips = SysConfigParams.getConfig("skip.log.cmd");
           if(StringUtils.isNotEmpty(strSkips)){
               String [] cmds = strSkips.split(",");
               for(String cmd : cmds){
                   logSkipCmdSet.add(cmd);
               }
           }
        }
        if(logSkipCmdSet.contains(urlInfo.getCmd())){
            return false;
        }
        if(funcService == null){
            funcService = (IFuncService) SpringContextUtil.getBean("funcService");
        }
        Map<String,Object> countParmas = new HashMap<>();
        String controller = urlInfo.getController();
        if(controller.startsWith("/")){
            controller = controller.replaceFirst("/","");
        }
        countParmas.put("controller",controller);
        countParmas.put("funcCode",urlInfo.getCmd());
        countParmas.put("isLog",1);
        try{
            if(funcService.count(countParmas )> 0){
                return true;
            }
        }catch (Exception x){
            logger.error("",x);
        }
        return false;
    }


    public LogInterceptor() {
        super();
    }

    @Override
    public boolean beforeExecute(HttpServletRequest request, HttpServletResponse response, Object arg2) {
        //这里执行日志记录
        ILoginUserContext userContext =  (ILoginUserContext)  SpringContextUtil.getBean("loginUserCtx");
        LoginUser user = null;
        try{
            user = userContext.getCurrentUser();
        }catch (Exception x){
            logger.error("",x);
        }
        if(user != null){
            UrlInfo urlInfo = AdminControllerHelper.getControllerAndCmd(request);
            String url = urlInfo.getUrl();
            if(url.contains("/v1/logout")){
                LogParams logParams = new LogParams();
                logParams.setDesp("logout");
                logParams.setUrlInfo(urlInfo);
                logParams.setUser(user);
                Object Obj = OperatorDataHolder.getData();
                logParams.setData(Obj);
                LogTasks tasks = new LogTasks(logParams);
                ExecuteThreadTask.exeTask(tasks);
            }
        }
        return true;
    }

    @Override
    public void afterExecute(HttpServletRequest arg0, HttpServletResponse arg1, Exception arg3) {
        //这里执行日志记录
        ILoginUserContext userContext =  (ILoginUserContext)  SpringContextUtil.getBean("loginUserCtx");
        LoginUser user = null;
        try{
            user = userContext.getCurrentUser();
        }catch (Exception x){
            logger.error("",x);
        }
        if(user != null){
            UrlInfo urlInfo = AdminControllerHelper.getControllerAndCmd(arg0);
            String url = urlInfo.getUrl();
            boolean need2log = false;
            LogParams logParams = new LogParams();
            if(url.contains("/v1/login")){
                logParams.setDesp("login");
                need2log = true;
            }else{
                 need2log = need2log(urlInfo);
            }
            if(need2log){
                logParams.setUrlInfo(urlInfo);
                logParams.setUser(user);
                Object Obj = OperatorDataHolder.getData();
                logParams.setData(Obj);
                LogTasks tasks = new LogTasks(logParams);
                ExecuteThreadTask.exeTask(tasks);
            }
        }
    }
}
